import { useState, useEffect } from "react";
import { useAuth } from "@/contexts/authContext.js";
import { useTheme } from "@/hooks/useTheme.js";
import { toast } from "sonner";
import { motion } from "framer-motion";

// 设置页面 - 实现用户偏好设置、主题切换、账户安全等功能
export default function Settings() {
  const { user, logout } = useAuth();
  const { theme, toggleTheme, isDark } = useTheme();
  const [loading, setLoading] = useState(true);
  const [profile, setProfile] = useState({
    name: "",
    email: "",
    avatar: "",
    bio: ""
  });
  const [notificationSettings, setNotificationSettings] = useState({
    emailNotifications: true,
    pushNotifications: true,
    activityAlerts: true,
    marketingEmails: false
  });
  const [passwordForm, setPasswordForm] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: ""
  });
  const [isEditingProfile, setIsEditingProfile] = useState(false);
  const [activeTab, setActiveTab] = useState("profile");
  
  // 模拟数据加载
  useEffect(() => {
    const fetchSettings = () => {
      // 模拟API请求延迟
      setTimeout(() => {
        // 基于当前用户设置模拟数据
        setProfile({
          name: user?.username === 'admin' ? '管理员' : user?.username || '用户',
          email: user?.username === 'admin' ? 'admin@example.com' : 'user@example.com',
          avatar: `https://space.coze.cn/api/coze_space/gen_image?image_size=square&prompt=user%20avatar%20${user?.username || 'user'}`,
          bio: user?.role === 'admin' ? '系统管理员，负责维护整个系统' : '系统普通用户'
        });
        
        // 从本地存储加载通知设置
        const savedNotifications = localStorage.getItem('notificationSettings');
        if (savedNotifications) {
          setNotificationSettings(JSON.parse(savedNotifications));
        }
        
        setLoading(false);
      }, 800);
    };
    
    fetchSettings();
  }, [user]);
  
  // 处理个人资料表单变化
  const handleProfileChange = (e) => {
    const { name, value } = e.target;
    setProfile(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 保存个人资料
  const handleSaveProfile = () => {
    // 模拟保存操作
    setIsEditingProfile(false);
    toast.success("个人资料已更新");
  };
  
  // 处理通知设置变化
  const handleNotificationChange = (e) => {
    const { name, checked } = e.target;
    const updatedSettings = {
      ...notificationSettings,
      [name]: checked
    };
    setNotificationSettings(updatedSettings);
    // 保存到本地存储
    localStorage.setItem('notificationSettings', JSON.stringify(updatedSettings));
  };
  
  // 处理密码表单变化
  const handlePasswordChange = (e) => {
    const { name, value } = e.target;
    setPasswordForm(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 更改密码
  const handleChangePassword = (e) => {
    e.preventDefault();
    
    // 表单验证
    if (!passwordForm.currentPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
      toast.error("请填写所有密码字段");
      return;
    }
    
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      toast.error("新密码和确认密码不匹配");
      return;
    }
    
    // 模拟密码更新
    toast.success("密码已成功更改");
    
    // 重置表单
    setPasswordForm({
      currentPassword: "",
      newPassword: "",
      confirmPassword: ""
    });
  };
  
  // 处理账户删除
  const handleDeleteAccount = () => {
    if (window.confirm("确定要删除您的账户吗？此操作不可撤销！")) {
      // 模拟账户删除
      toast.success("账户已删除");
      logout();
    }
  };
  
  // 渲染标签页内容
  const renderTabContent = () => {
    if (loading) {
      return (
        <div className="py-12 text-center">
          <div className="inline-block animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-indigo-600"></div>
          <p className="mt-4 text-gray-500 dark:text-gray-400">加载设置中...</p>
        </div>
      );
    }
    
    switch (activeTab) {
      case "profile":
        return renderProfileTab();
      case "notifications":
        return renderNotificationsTab();
      case "security":
        return renderSecurityTab();
      case "appearance":
        return renderAppearanceTab();
      default:
        return renderProfileTab();
    }
  };
  
  // 个人资料标签页
  const renderProfileTab = () => (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="flex flex-col sm:flex-row items-center space-y-4 sm:space-y-0 sm:space-x-6">
        <div className="relative">
          <div className="w-24 h-24 rounded-full overflow-hidden border-4 border-white dark:border-gray-800 shadow-lg">
            <img 
              src={profile.avatar} 
              alt="用户头像" 
              className="w-full h-full object-cover"
            />
          </div>
          {isEditingProfile && (
            <button className="absolute bottom-0 right-0 bg-indigo-600 text-white rounded-full p-2 shadow-lg hover:bg-indigo-700 transition-colors">
              <i className="fa-solid fa-camera"></i>
            </button>
          )}
        </div>
        <div className="text-center sm:text-left">
          <h3 className="text-xl font-bold text-gray-900 dark:text-white">{profile.name}</h3>
          <p className="text-gray-600 dark:text-gray-400">{profile.email}</p>
          <p className="text-sm text-gray-500 dark:text-gray-500 mt-1">角色: {user?.role === 'admin' ? '管理员' : '普通用户'}</p>
        </div>
        {!isEditingProfile && (
          <button
            onClick={() => setIsEditingProfile(true)}
            className="ml-auto px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors flex items-center"
          >
            <i className="fa-solid fa-pen-to-square mr-2"></i> 编辑资料
          </button>
        )}
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div className="space-y-4">
          <div>
            <label
              htmlFor="name"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              姓名
            </label>
            <input
              type="text"
              id="name"
              name="name"
              value={profile.name}
              onChange={handleProfileChange}
              disabled={!isEditingProfile}
              className={`w-full px-4 py-2 rounded-lg border ${
                isEditingProfile 
                  ? 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent' 
                  : 'border-transparent bg-transparent dark:bg-transparent'
              } text-gray-900 dark:text-white transition-colors`}
            />
          </div>
          
          <div>
            <label
              htmlFor="email"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              邮箱
            </label>
            <input
              type="email"
              id="email"
              name="email"
              value={profile.email}
              onChange={handleProfileChange}
              disabled={!isEditingProfile}
              className={`w-full px-4 py-2 rounded-lg border ${
                isEditingProfile 
                  ? 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent' 
                  : 'border-transparent bg-transparent dark:bg-transparent'
              } text-gray-900 dark:text-white transition-colors`}
            />
          </div>
        </div>
        
        <div>
          <label
            htmlFor="bio"
            className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
          >
            个人简介
          </label>
          <textarea
            id="bio"
            name="bio"
            value={profile.bio}
            onChange={handleProfileChange}
            disabled={!isEditingProfile}
            rows={4}
            className={`w-full px-4 py-2 rounded-lg border ${
              isEditingProfile 
                ? 'border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 focus:ring-2 focus:ring-indigo-500 focus:border-transparent' 
                : 'border-transparent bg-transparent dark:bg-transparent'
            } text-gray-900 dark:text-white transition-colors resize-none`}
          ></textarea>
        </div>
      </div>
      
      {isEditingProfile && (
        <div className="flex justify-end space-x-3 pt-4">
          <button
            onClick={() => {
              setIsEditingProfile(false);
              // 重置表单
              setProfile({
                name: user?.username === 'admin' ? '管理员' : user?.username || '用户',
                email: user?.username === 'admin' ? 'admin@example.com' : 'user@example.com',
                avatar: profile.avatar,
                bio: user?.role === 'admin' ? '系统管理员，负责维护整个系统' : '系统普通用户'
              });
            }}
            className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
          >
            取消
          </button>
          <button
            onClick={handleSaveProfile}
            className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors"
          >
            保存更改
          </button>
        </div>
      )}
    </motion.div>
  );
  
  // 通知设置标签页
  const renderNotificationsTab = () => (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">通知首选项</h3>
        
        <div className="space-y-4">
          {[
            { 
              id: 'emailNotifications', 
              label: '邮件通知', 
              description: '接收重要更新和系统通知的电子邮件' 
            },
            { 
              id: 'pushNotifications', 
              label: '推送通知', 
              description: '在您的设备上接收推送通知' 
            },
            { 
              id: 'activityAlerts', 
              label: '活动提醒', 
              description: '接收有关账户活动的提醒' 
            },
            { 
              id: 'marketingEmails', 
              label: '营销邮件', 
              description: '接收产品更新和促销信息' 
            }
          ].map((item) => (
            <div key={item.id} className="flex items-start justify-between py-2">
              <div>
                <label
                  htmlFor={item.id}
                  className="text-base font-medium text-gray-900 dark:text-white"
                >
                  {item.label}
                </label>
                <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                  {item.description}
                </p>
              </div>
              <div className="ml-4 flex-shrink-0">
                <input
                  type="checkbox"
                  id={item.id}
                  name={item.id}
                  checked={notificationSettings[item.id]}
                  onChange={handleNotificationChange}
                  className="h-5 w-5 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                />
              </div>
            </div>
          ))}
        </div>
      </div>
      
      <div className="bg-yellow-50 dark:bg-yellow-900/20 rounded-xl p-6 border border-yellow-200 dark:border-yellow-800">
        <div className="flex items-start">
          <div className="flex-shrink-0 pt-0.5">
            <i className="fa-solid fa-circle-info text-yellow-500 dark:text-yellow-400"></i>
          </div>
          <div className="ml-3">
            <h3 className="text-sm font-medium text-yellow-800 dark:text-yellow-300">通知设置说明</h3>
            <div className="mt-2 text-sm text-yellow-700 dark:text-yellow-400">
              <p>您可以随时更改通知首选项。系统通知对于账户安全和重要更新至关重要，建议保持开启。</p>
            </div>
          </div>
        </div>
      </div>
    </motion.div>
  );
  
  // 安全设置标签页
  const renderSecurityTab = () => (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">更改密码</h3>
        
        <form onSubmit={handleChangePassword} className="space-y-4">
          <div>
            <label
              htmlFor="currentPassword"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              当前密码
            </label>
            <input
              type="password"
              id="currentPassword"
              name="currentPassword"
              value={passwordForm.currentPassword}
              onChange={handlePasswordChange}
              className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors"
              placeholder="请输入当前密码"
            />
          </div>
          
          <div>
            <label
              htmlFor="newPassword"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              新密码
            </label>
            <input
              type="password"
              id="newPassword"
              name="newPassword"
              value={passwordForm.newPassword}
              onChange={handlePasswordChange}
              className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors"
              placeholder="请输入新密码"
            />
            <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              密码长度至少8位，包含字母和数字
            </p>
          </div>
          
          <div>
            <label
              htmlFor="confirmPassword"
              className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
            >
              确认新密码
            </label>
            <input
              type="password"
              id="confirmPassword"
              name="confirmPassword"
              value={passwordForm.confirmPassword}
              onChange={handlePasswordChange}
              className="w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-colors"
              placeholder="请再次输入新密码"
            />
          </div>
          
          <div className="pt-2">
            <button
              type="submit"
              className="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-lg transition-colors"
            >
              更改密码
            </button>
          </div>
        </form>
      </div>
      
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">账户安全</h3>
        
        <div className="space-y-4">
          <div className="flex items-center justify-between py-3 border-b border-gray-200 dark:border-gray-700">
            <div>
              <h4 className="text-base font-medium text-gray-900 dark:text-white">双重认证</h4>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                为您的账户添加额外的安全层
              </p>
            </div>
            <button className="px-3 py-1 bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200 rounded-lg text-sm transition-colors">
              未启用
            </button>
          </div>
          
          <div className="flex items-center justify-between py-3 border-b border-gray-200 dark:border-gray-700">
            <div>
              <h4 className="text-base font-medium text-gray-900 dark:text-white">登录历史</h4>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                查看最近的账户活动
              </p>
            </div>
            <button className="px-3 py-1 bg-indigo-100 hover:bg-indigo-200 dark:bg-indigo-900 dark:hover:bg-indigo-800 text-indigo-800 dark:text-indigo-200 rounded-lg text-sm transition-colors">
                查看
            </button>
          </div>
          
          <div className="flex items-center justify-between py-3">
            <div>
              <h4 className="text-base font-medium text-gray-900 dark:text-white">删除账户</h4>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                永久删除您的账户和所有数据
              </p>
            </div>
            <button 
              onClick={handleDeleteAccount}
              className="px-3 py-1 bg-red-100 hover:bg-red-200 dark:bg-red-900 dark:hover:bg-red-800 text-red-800 dark:text-red-200 rounded-lg text-sm transition-colors"
            >
                删除
            </button>
          </div>
        </div>
      </div>
      
      <div className="bg-red-50 dark:bg-red-900/20 rounded-xl p-6 border border-red-200 dark:border-red-800">
        <div className="flex items-start">
          <div className="flex-shrink-0 pt-0.5">
            <i className="fa-solid fa-triangle-exclamation text-red-500 dark:text-red-400"></i>
          </div>
          <div className="ml-3">
            <h3 className="text-sm font-medium text-red-800 dark:text-red-300">注意</h3>
            <div className="mt-2 text-sm text-red-700 dark:text-red-400">
              <p>删除账户将永久删除所有数据，包括个人信息、产品数据和用户数据。此操作无法撤销。</p>
            </div>
          </div>
        </div>
      </div>
    </motion.div>
  );
  
  // 外观设置标签页
  const renderAppearanceTab = () => (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">主题设置</h3>
        
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <div>
              <h4 className="text-base font-medium text-gray-900 dark:text-white">主题模式</h4>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                选择您偏好的界面主题
              </p>
            </div>
            
            <div className="flex items-center space-x-3">
              <button
                onClick={() => document.documentElement.classList.remove('dark')}
                className={`px-3 py-1 rounded-lg text-sm transition-colors ${
                  !isDark 
                    ? 'bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 shadow-sm border border-gray-200 dark:border-gray-600' 
                    : 'bg-transparent text-gray-500 dark:text-gray-400'
                }`}
              >
                浅色
              </button>
              
              <button
                onClick={() => {
                  document.documentElement.classList.toggle('dark');
                  toggleTheme();
                }}
                className={`px-3 py-1 rounded-lg text-sm transition-colors ${
                  isDark 
                    ? 'bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 shadow-sm border border-gray-200 dark:border-gray-600' 
                    : 'bg-transparent text-gray-500 dark:text-gray-400'
                }`}
              >
                深色
              </button>
              
              <button
                onClick={() => {
                  const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
                  if (prefersDark !== isDark) {
                    toggleTheme();
                  }
                }}
                className={`px-3 py-1 rounded-lg text-sm transition-colors ${
                  localStorage.getItem('theme') === null 
                    ? 'bg-white dark:bg-gray-700 text-gray-800 dark:text-gray-200 shadow-sm border border-gray-200 dark:border-gray-600' 
                    : 'bg-transparent text-gray-500 dark:text-gray-400'
                }`}
              >
                跟随系统
              </button>
            </div>
          </div>
          
          <div className="pt-4">
            <h4 className="text-base font-medium text-gray-900 dark:text-white mb-3">主题预览</h4>
            <div className={`p-4 rounded-lg border ${isDark ? 'bg-gray-800 border-gray-700' : 'bg-white border-gray-200'} shadow-sm`}>
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 rounded-full bg-indigo-100 dark:bg-indigo-900 flex items-center justify-center text-indigo-600 dark:text-indigo-300">
                  <i className="fa-solid fa-user"></i>
                </div>
                <div>
                  <h5 className={`text-sm font-medium ${isDark ? 'text-gray-300' : 'text-gray-900'}`}>用户界面预览</h5>
                  <p className={`text-xs ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
                    这是当前主题下的界面元素样式
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">显示设置</h3>
        
        <div className="space-y-4">
          <div className="flex items-start justify-between py-2">
            <div>
              <label
                htmlFor="showSidebar"
                className="text-base font-medium text-gray-900 dark:text-white"
              >
                显示侧边栏
              </label>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                在管理页面显示侧边导航栏
              </p>
            </div>
            <div className="ml-4 flex-shrink-0">
              <input
                type="checkbox"
                id="showSidebar"
                defaultChecked={true}
                className="h-5 w-5 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
              />
            </div>
          </div>
          
          <div className="flex items-start justify-between py-2">
            <div>
              <label
                htmlFor="animateUI"
                className="text-base font-medium text-gray-900 dark:text-white"
              >
                动画效果
              </label>
              <p className="text-sm text-gray-500 dark:text-gray-400 mt-1">
                启用界面过渡和动画效果
              </p>
            </div>
            <div className="ml-4 flex-shrink-0">
              <input
                type="checkbox"
                id="animateUI"
                defaultChecked={true}
                className="h-5 w-5 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
              />
            </div>
          </div>
        </div>
      </div>
    </motion.div>
  );
  
  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex flex-col">
      {/* 顶部导航 */}
      <header className="bg-white dark:bg-gray-800 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex justify-between items-center">
            <div>
              <h1 className="text-xl font-bold text-gray-900 dark:text-white">设置</h1>
              <p className="text-sm text-gray-500 dark:text-gray-400">管理您的个人偏好和账户设置</p>
            </div>
          </div>
        </div>
      </header>
      
      {/* 主内容区 */}
      <main className="flex-grow max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* 标签页导航 */}
        <div className="border-b border-gray-200 dark:border-gray-700 mb-6">
          <nav className="-mb-px flex space-x-8 overflow-x-auto">
            {[
              { id: "profile", label: "个人资料", icon: "fa-user" },
              { id: "notifications", label: "通知", icon: "fa-bell" },
              { id: "security", label: "安全", icon: "fa-lock" },
              { id: "appearance", label: "外观", icon: "fa-palette" }
            ].map((tab) => (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id)}
                className={`py-4 px-1 border-b-2 font-medium text-sm whitespace-nowrap transition-colors ${
                  activeTab === tab.id
                    ? "border-indigo-600 text-indigo-600 dark:text-indigo-400"
                    : "border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300"
                }`}
              >
                <div className="flex items-center">
                  <i className={`fa-solid ${tab.icon} mr-2`}></i>
                  {tab.label}
                </div>
              </button>
            ))}
          </nav>
        </div>
        
        {/* 标签页内容 */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-sm p-6">
          {renderTabContent()}
        </div>
      </main>
      
      {/* 页脚 */}
      <footer className="bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 py-4 mt-8">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <p className="text-sm text-gray-500 dark:text-gray-400">
            © 2025 React学习管理系统 | 版本 1.0.0
          </p>
        </div>
      </footer>
    </div>
  );
}